package com.likou.second_challenge;

public class q2 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode(0);
        ListNode p = ans;
        int carry = 0;
        ListNode p1 = l1;
        ListNode p2 = l2;

        while (p1 != null && p2 != null) {
            p.next = new ListNode((p1.val + p2.val + carry) % 10);
            p = p.next;
            carry = (p1.val + p2.val + carry) / 10;

            p1 = p1.next;
            p2 = p2.next;
        }
        while (p2 != null) {
            p.next = new ListNode((p2.val + carry) % 10);
            p = p.next;
            carry = (p2.val + carry) / 10;
            p2 = p2.next;
        }

        while (p1 != null) {
            p.next = new ListNode((p1.val + carry) % 10);
            p = p.next;
            carry = (p1.val + carry) / 10;
            p1 = p1.next;
        }

        if (carry != 0) {
            p.next = new ListNode(carry);
        }
        return ans.next;
    }
}
